<?php

require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'LzUrlArgs.php';


/**
 *  URL manupulation class.
 *
 *  @author     GoniX aka Giedrius Dubinskas
 *  @created    2008-01-05
 */
class LzUrl
        extends LzPod
{
    public
    function __construct($url)
    {
        $parts  = parse_url($url);
        if (!is_array($parts))
            $parts  = array();

        $parts  += array(
                    'scheme'    => '',
                    'host'      => '',
                    'port'      => '',
                    'user'      => '',
                    'pass'      => '',
                    'path'      => '',
                    'query'     => '',
                    'fragment'  => '',
                );

        $args   = array();
        parse_str($parts['query'], $args);
        unset($parts['query']);

        $data   = $parts;
        $data['args']   = new LzUrlArgs($args);
        $data['path']   = Lz::def(new LzPath('/'))->add($parts['path']);

        parent::__construct($data);
    }


    public
    function __get($name)
    {
        if (!isset($this->data[$name]))
            throw new LzBadUsage($name);

        return $this->data[$name];
    }


    public
    function __set($name, $value)
    {
        // :TODO: gx 2008-01-15: more specific exception
        if (!isset($this->data[$name]))
            throw new LzBadUsage($name);

        if ('args' == $name)
            $value  = new LzUrlArgs($value);
        else if ('path' == $name)
            $value  = Lz::def(new LzPath('/'))->add($value);
        else
            $value  = (string)$value;

        $this->data[$name]  = $value;
    }


    public
    function __toString()
    {
        return $this->toStr();
    }


    public
    function toStr($delimiter = NULL)
    {
        $url    = '';
        if ('' !== $this->scheme)
            $url    = $this->scheme . '://';

        if ('' != $this->user)
        {
            $url    .= $this->user;
            if ('' != $this->pass)
                $url    .= ':' . $this->pass;
            $url    .= '@';
        }

        $url    .= $this->host;

        if ('' != $this->port)
            $url    .= ':' . $this->port;

        $url    .= $this->path;

        if ('' != $this->args->toStr($delimiter))
            $url    .= '?' . $this->args->toStr($delimiter);

        if ('' != $this->fragment)
            $url    .= '#' . $this->fragment;

        return $url;
    }


    public
    function toPath()
    {

    }
}



/**
 *  Inline constructor for LzUrl class.
 *
 *  @return [LzPath]
 *  @see    class LzPath
 */
function LzUrl($url)
{
    return new LzUrl($url);
}

